package 链表.双指针;

/**
 * https://leetcode.cn/problems/merge-two-sorted-lists/?favorite=2cktkvj
 *
 * 题解：题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493134&idx=1&sn=88aff096dd25d40acbc6e0a79bd1038f&chksm=9bd41806aca3911019d1b8b1cfd9f8dda7e4663ef9cfd2603728ae7c874f06a218677b23db94&scene=178&cur_album_id=2165022824317485057#rd
 */
public class _21_合并两个有序链表 {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        ListNode sentinal = new ListNode(-1);
        ListNode p = sentinal;
        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                p.next = list2;
                list2 = list2.next;
            } else {
                p.next = list1;
                list1 = list1.next;
            }
        }

        if (list1 != null) {
            p.next = list1;
        }
        if (list2 != null) {
            p.next = list2;
        }
        return sentinal.next;
    }
}
